// index.js
// 获取应用实例
// import {
//   genTestUserSig
// } from '../../debug/GenerateTestUserSig'
const utils = require("../../utils/utils");
const app = getApp()
Page({
    data: {
        timer: null,
        mourning: '-1',
        userIDToSearch: '',
        searchResultShow: false,
        indexData: {},
        printId: '',
        firstOpen: 0,
        showAdv: false,
        tipsShow: false,
        chooseImageArray: [],
        list: [],
        loadingTag: 4,
        ds: 0,
        text: '',
        //初始滚动距离
        distance: 0,
        //时间间隔
        interver: 30,
        //滚动速度
        pace: 1,
        size: 14
    },
    goToPrice() {
        wx.navigateTo({
            url: '../print/priceList/priceList?sn=' + this.data.printId,
        })
    },
    tipshide() {
        this.setData({
            tipsShow: false
        })
    },
    showAdvs() {
        this.setData({
            showAdv: true
        })
    },
    hideAdvs() {
        this.setData({
            showAdv: false
        })
    },
    goUrl(e) {
        var url = e.currentTarget.dataset.url;
        if (url == '/pages/print/list/list') {
            app.get_local('AccToken').then(res => {
                if (utils.is_define(res)) {
                    app.get_local('machineQrCode').then(res => {
                        if (utils.is_define(res)) {
                            wx.navigateTo({
                                url: url,
                            })
                        } else {
                            utils.toast("请先选择打印机");
                        }
                    })
                } else {
                    wx.navigateTo({
                        url: '../my/login/login',
                    })
                }
            })
        } else {
            wx.navigateTo({
                url: url,
            })
        }
    },
    goToLink(e) {
        var url = e.currentTarget.dataset.link;
        var content = e.currentTarget.dataset.content;
        var id = e.currentTarget.dataset.id;
        var title = e.currentTarget.dataset.title;
        if (content=='true') {
            //信息详情
            wx.navigateTo({
                url: '/pages/my/pictureAdv/pictureAdv?id=' + id + '&name=' + title
            })
        } else if (utils.is_define(url)) {
            if (url.indexOf('pages') != -1) {
                if (url.indexOf('ttyyh') != -1) {
                   
                } else {
                    wx.navigateTo({
                        url: url,
                    })
                }
                return false;
            }
            if (url.indexOf('https') != -1) {
                wx.navigateTo({
                    url: '../my/agreement/agreement?url=' + url
                })
                return false;
            }
        }else{

        }
    },
    //项目跳转
    goItemUrl(e) {
        var support = e.currentTarget.dataset.issupport;
        var url = e.currentTarget.dataset.url;
        var that = this;
        var code = e.currentTarget.dataset.code;
        var notice = e.currentTarget.dataset.notice;
        var status = e.currentTarget.dataset.status;
        if (support == false) {
            utils.toast('QQ暂不支持此方式');
            return false;
        }
        if (!status) {
            if (utils.is_define(notice)) {
                utils.toast(notice);
            } else {
                utils.toast('当前打印机不支持此方式');
            }

            return false;
        }
        app.get_local('AccToken').then(res => {
            if (utils.is_define(res)) {
                app.get_local('machineQrCode').then(res => {
                    if (utils.is_define(res) && (that.data.mercShopDevice.onlineStatus != 1 || that.data.mercShopDevice.printStatus != 1)) {
                        that.getInfoAgain(function (res) {
                            wx.navigateTo({
                                url: url,
                            })
                        });
                        return false;
                    }
                    if (utils.is_define(res) || code == 'idPhoto') {
                        wx.navigateTo({
                            url: url,
                        })
                    } else {
                        utils.toast("请先选择打印机");
                    }
                })
            } else {
                wx.navigateTo({
                    url: '../my/login/login',
                })
            }
        })
    },
    //如果机器异常，点击分类时再获取一次
    getInfoAgain(callback) {
        var that = this;
        that.selectComponent("#loading").showLoadingCus();
        utils.request('home/deviceInfo', {}, function (res) {
            that.selectComponent("#loading").hideLoadingCus();
            if (res.data.code == 200) {
                wx.setStorageSync('virtualMachine', res.data.data.virtualMachine)
                wx.setStorageSync('minPrice', res.data.data.minPrice)
                wx.setStorageSync('sendTime', res.data.data.remarks)
                if (res.data.data.printStatus != 1 || res.data.data.onlineStatus != 1) {
                    wx.showModal({
                        title: '温馨提示',
                        content: '该设备暂不可用，是否拨打客服热线进行求助',
                        showCancel: true,
                        success(res) {
                            if (res.confirm) {
                                wx.makePhoneCall({
                                    phoneNumber: '4000921588',
                                })
                            } else if (res.cancel) {

                            }
                        }
                    })
                    that.setData({
                        mercShopDevice: res.data.data,
                        tipsShow: true
                    })
                    return false;
                }
                callback(1)
                that.setData({
                    mercShopDevice: res.data.data,
                    tipsShow: false
                })
            } else {
                utils.toast(res.data.msg)
            }
        })
    },
    //拍照调取相册
    getPhoto(type, code) {
        var that = this;
        wx.chooseImage({
            count: 9,
            sizeType: ['original'],
            sourceType: [type],
            success(res) {
                if (code == '28542179') {
                    that.setData({
                        loadingTag: 5,
                        chooseImageArray: res.tempFilePaths
                    })
                    wx.showLoading({
                        title: '请稍候',
                    })
                    //轮巡判断上传
                    that.uploadFileImg(that.data.chooseImageArray[0], 0);
                }
            }
        })
    },
    getPhoto1(code) {
        var that = this;
        wx.chooseMessageFile({
            count: 9,
            type: 'image',
            success(res) {
                if (code == '28542179') {
                    var array = [];
                    for (var i = 0; i < res.tempFiles.length; i++) {
                        array.push(res.tempFiles[i].path)
                    }
                    that.setData({
                        loadingTag: 5,
                        chooseImageArray: array
                    })
                    wx.showLoading({
                        title: '请稍候',
                    })
                    //轮巡判断上传
                    that.uploadFileImg(that.data.chooseImageArray[0], 0);
                }
            }
        })
    },
    uploadFileImg(url, index) {
        var that = this;
        var list = that.data.list;
        var imgs = that.data.chooseImageArray;
        var indexs = parseInt(index) + 1;
        var str = '上传 ' + indexs + '/' + that.data.chooseImageArray.length + '张';
        wx.showLoading({
            title: str,
        })
        utils.uploadfile(url, '', function (res) {
            var data = JSON.parse(res.data)
            if (data.code == 1) {
                var imgurl = data.url;
                var obj = {};
                obj.url = imgurl;
                obj.isFull = -1;
                obj.isColor = data.color;
                obj.num = 1;
                obj.name = '图片'
                list.push(obj);
                that.setData({
                    list: list
                })
                if (index == imgs.length - 1) {
                    that.setData({
                        chooseImageArray: []
                    })
                    that.submitPhoto();
                } else {
                    that.uploadFileImg(imgs[index + 1], index + 1)
                }
            } else {
                wx.hideLoading()
                utils.toast(data.msg);
                that.setData({
                    list: [],
                    chooseImageArray: [],
                    loadingTag: 4
                })
            }
        })

    },
    submitPhoto() {
        var that = this;
        app.get_local('machineQrCode').then(res => {
            var data = {
                code: '28542179',
                sn: res,
                file: JSON.stringify(that.data.list),
            }
            utils.request('Order/addCartAll', data, function (res) {
                that.setData({
                    chooseImageArray: [],
                    list: [],
                    loadingTag: 4
                })
                if (res.data.code == 1) {
                    wx.hideLoading()
                    wx.navigateTo({
                        url: '/pages/print/list/list',
                    })
                } else {
                    wx.hideLoading()
                    utils.toast(res.data.msg)
                }
            })
        })

    },
    onReady: function () {

    },
    onLoad(e) {
        var that = this;
        if (utils.is_define(e.q)) {
            const q = decodeURIComponent(e.q)
            var nums = q.split('/')
            wx.setStorageSync('machineQrCode', nums[nums.length - 1])
            that.setData({
                printId: nums[nums.length - 1]
            })
            wx.showLoading({
                title: '正在添加打印机',
            })
            // that.getIndexList()
            that.getIndexPage()
        } else if (utils.is_define(e.sn)) {
            wx.setStorageSync('machineQrCode', e.sn)
            that.setData({
                printId: e.sn
            })
            wx.showLoading({
                title: '正在添加打印机',
            })
            // that.getIndexList()
            that.getIndexPage()
        } else {
            app.get_local('machineQrCode').then(res => {
                if (utils.is_define(res)) {
                    that.setData({
                        printId: res
                    })
                    // that.getIndexList()
                    that.getIndexPage()
                } else {
                    // that.getIndexList()
                    that.getIndexPage()
                }
            })
        }
    },
    getIndexPage() {
        //首页机器配置
        this.indexConfig()
        //首页头部按钮
        this.indexHomeBtn()
        //首页服务项目
        this.indexServiceItem()
        //首页轮播图
        this.indexScrollAd()
        //首页弹屏广告
        this.indexDialogAdList()
        //门店机器详情
        this.indexShopDevice()
    },
    indexShopDevice() {
        var that = this;
        utils.request('home/deviceInfo', {}, function (res) {
            if (that.data.loadingTag == 4) {
                wx.hideLoading()
            }
            if (res.data.code == 200) {
                if (utils.isEmptyObject(res.data.data)) {
                    that.setData({
                        mercShopDevice: {},
                        tipsShow: false,
                        printId: ''
                    })
                    return false;
                }
                wx.setStorageSync('virtualMachine', res.data.data.virtualMachine)
                wx.setStorageSync('minPrice', res.data.data.minPrice)
                wx.setStorageSync('sendTime', res.data.data.remarks)
                //水平一行文字向左滚动，滚动完了从屏幕右侧出现，继续滚动
                if (res.data.data.expireTips.length > 0) {
                    wx.removeStorageSync('machineQrCode')
                    wx.showModal({
                        title: '温馨提示',
                        content: res.data.data.expireTips,
                        showCancel: false,
                        success(res) {
                            if (res.confirm) {
                                wx.makePhoneCall({
                                    phoneNumber: '4000921588',
                                })
                            } else if (res.cancel) {

                            }
                        }
                    })
                    //二维码到期
                    that.setData({
                        mercShopDevice: {},
                        tipsShow: false,
                        printId: ''
                    })
                    return false;
                }
                if (res.data.data.productionStatus != 1 || res.data.data.status != 1) {
                    wx.removeStorageSync('machineQrCode')
                    wx.showModal({
                        title: '温馨提示',
                        content: '该设备暂不可用，是否拨打客服热线进行求助',
                        showCancel: true,
                        success(res) {
                            if (res.confirm) {
                                wx.makePhoneCall({
                                    phoneNumber: '4000921588',
                                })
                            } else if (res.cancel) {

                            }
                        }
                    })
                    that.setData({
                        mercShopDevice: {},
                        tipsShow: false,
                        printId: ''
                    })
                    return false;
                }
                var windowWidth = parseFloat(wx.getSystemInfoSync().windowWidth / 2);
                var str = res.data.data.welcome ? res.data.data.welcome : '欢迎光临喵小匠服务商铺——'
                that.setData({
                    mercShopDevice: res.data.data,
                    tipsShow: true,
                    text: str + res.data.data.shopName,
                    distance: windowWidth
                })
                //获取文字长度
                var a = that.getLenPx(that.data.text, that.data.size)
                //获取屏幕宽度

                that.setData({
                    length: a,
                    windowWidth: windowWidth
                });
                that.run();
            } else {
                utils.toast(res.data.msg)
            }
        })
    },
    getLenPx(str, font_size) {
        var str_leng = str.replace(/[^\x00-\xff]/gi, 'aa').length;
        return str_leng * font_size / 2
    },
    run: function () {
        var that = this;
        that.data.timer = setInterval(function () {
            //文字一直移动到末尾
            if (-that.data.distance < that.data.length) {
                that.setData({
                    distance: that.data.distance - that.data.pace
                });
            } else {
                clearInterval(that.data.timer);
                that.setData({
                    distance: that.data.windowWidth
                });
                that.run();
            }
        }, that.data.interver);
    },
    indexConfig() {
        var that = this;
        utils.request('config/config', {}, function (res) {
            that.setData({
                mourning: res.data.data.mourning,
                shareImg: res.data.data.wxAppletShareBg,
                shareTitle: res.data.data.wxAppletShareTitle
            })
        })
    },
    indexHomeBtn() {
        var that = this;
        utils.request('home/homeTopBtn', {}, function (res) {
            that.setData({
                homeTopBtn: res.data.data
            })
        })
    },
    indexServiceItem() {
        var that = this;
        utils.request('home/scrollAdList', {}, function (res) {
            that.setData({
                scrollAdList: res.data.data
            })
        })
    },
    indexScrollAd() {
        var that = this;
        utils.request('home/serviceItem', {}, function (res) {
            that.setData({
                serviceItem: res.data.data
            })
        })
    },
    indexDialogAdList() {
        var that = this;
        utils.request('home/dialogAdList', {}, function (res) {
            that.setData({
                dialogAdList: res.data.data
            })
            if (utils.is_define(res.data.data) && (!utils.is_define(wx.getStorageSync('advId')))) {
                wx.setStorageSync('advId', res.data.data[0].id)
                that.setData({
                    advId: 1,
                    showAdv: true
                })
            } else {
                that.setData({
                    advId: 0,
                    showAdv: false
                })
            }
        })
    },
    onShow() {
        var that = this;
        clearInterval(that.data.timer);
        var timestamp = Date.parse(new Date());
        var expiration = timestamp + 6000000;
        var data_expiration = wx.getStorageSync("data_expiration");
        if (data_expiration) {
            if (timestamp > data_expiration) {
                wx.setStorageSync("data_expiration", expiration)
                wx.setStorageSync("advId", '')
            }
        } else {
            wx.setStorageSync("data_expiration", expiration)
        }
        if (that.data.firstOpen == 1) {
            app.get_local('machineQrCode').then(res => {
                if (utils.is_define(res)) {
                    that.setData({
                        printId: res
                    })
                    that.getIndexPage()
                    // that.getIndexList()
                } else {
                    that.getIndexPage()
                    // that.getIndexList()
                }
            })
        } else {
            that.setData({
                firstOpen: 1
            })
        }
    },
    onUnload: function () {
        clearInterval(this.data.timer);
        // this.TUICalling.destroyed()
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        var that = this;
        return {
            title: that.data.shareTitle,
            imageUrl: that.data.shareImg,
            path: '/pages/index/index?sn=' + that.data.printId,
        }
    }
})